/**
* Copyright (C) 2021 All rights reserved.
*
* @file main.h
* @author Wang Haibin
* @email wanghaibin@qiyi.com
* @date Tue Apr 11 16:18:36 CST 2023
* @brief  解析str字符串, 从后向前解析, 以空格为分割, 每组最后一个/的内容是组名
*/

#include <string.h>
#include <stdio.h>
#include <ctype.h>

void parse_groups(const char * domains) {
    printf("len=%zd, data=%s=======\n", strlen(domains), domains);
    if(NULL==domains || 0==strlen(domains)) {
        return;
    }
    const char * pos = domains + strlen(domains)-1;
    const char *end = pos;
    char group[128] = {0};
    char domain[128] = {0};
    while(pos>=domains) {
        if(isspace(*pos)) {
            if(0!=strlen(group)) {
                memset(domain, '\0', 128);
                memcpy(domain, pos+1, end-pos-1);
                if(end-pos-1>1) { //
                    printf("%s:%d group=%s, domain=%s, end-pos=%d\n",__FILE__, __LINE__, group, domain, (int)(end-pos));
                }
                memset(group, '\0', 128);
                end = pos;
            } else { // deal sufix multi space
                end = pos-1;
            }
        } else if(*pos=='/') {
            if(0==strlen(group)) {
                memset(group, '\0', 128);
                memcpy(group, pos+1, end-pos);
            } else {
                memset(domain, '\0', 128);
                memcpy(domain, pos+1, end-pos-1);
                if(end-pos-1 >1) {
                    printf("%s:%d group=%s, domain=%s, end-pos=%d\n",__FILE__, __LINE__, group, domain, (int)(end-pos));
                }
            }
            end = pos;
        }
        if(pos==domains && end>pos) { // deal pre multi space
            memset(domain, '\0', 128);
            memcpy(domain, pos, end-pos);
            printf("%s:%d group=%s, domain=%s, end-pos=%d\n",__FILE__, __LINE__, group, domain, (int)(end-pos));
        }
        pos--;
    }
}

int main()
{
    const char* str = "         /////adfadf.com/group0 /abc.com/mm.com/mmm.com/group1            bbb.com/group2           ";
    parse_groups(str);
}
